<!DOCTYPE HTML>
<html lang="en">


<head>
    <meta charset="utf-8">
    <meta name="keywords" content="Opencv学习笔记, Friats">
    <meta name="description" content="">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
    <meta name="renderer" content="webkit|ie-stand|ie-comp">
    <meta name="mobile-web-app-capable" content="yes">
    <meta name="format-detection" content="telephone=no">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
    <!-- Global site tag (gtag.js) - Google Analytics -->


    <title>Opencv学习笔记 | Friats</title>
    <link rel="icon" type="image/png" href="/blog/favicon.png">

    <link rel="stylesheet" type="text/css" href="/blog/libs/awesome/css/all.css">
    <link rel="stylesheet" type="text/css" href="/blog/libs/materialize/materialize.min.css">
    <link rel="stylesheet" type="text/css" href="/blog/libs/aos/aos.css">
    <link rel="stylesheet" type="text/css" href="/blog/libs/animate/animate.min.css">
    <link rel="stylesheet" type="text/css" href="/blog/libs/lightGallery/css/lightgallery.min.css">
    <link rel="stylesheet" type="text/css" href="/blog/css/matery.css">
    <link rel="stylesheet" type="text/css" href="/blog/css/my.css">

    <script src="/blog/libs/jquery/jquery.min.js"></script>
	
<meta name="generator" content="Hexo 5.0.2"><link rel="alternate" href="/blog/atom.xml" title="Friats" type="application/atom+xml">
<link rel="stylesheet" href="/blog/css/prism-tomorrow.css" type="text/css"></head>


<body>
    <header class="navbar-fixed">
    <nav id="headNav" class="bg-color nav-transparent">
        <div id="navContainer" class="nav-wrapper container">
            <div class="brand-logo">
                <a href="/blog/" class="waves-effect waves-light">
                    
                    <img src="/blog/medias/logo.png" class="logo-img" alt="LOGO">
                    
                    <span class="logo-span">Friats</span>
                </a>
            </div>
            

<a href="#" data-target="mobile-nav" class="sidenav-trigger button-collapse"><i class="fas fa-bars"></i></a>
<ul class="right nav-menu">
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/blog/" class="waves-effect waves-light">
      
      <i class="fas fa-home" style="zoom: 0.6;"></i>
      
      <span>Index</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/blog/tags" class="waves-effect waves-light">
      
      <i class="fas fa-tags" style="zoom: 0.6;"></i>
      
      <span>Tags</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/blog/categories" class="waves-effect waves-light">
      
      <i class="fas fa-bookmark" style="zoom: 0.6;"></i>
      
      <span>Categories</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/blog/archives" class="waves-effect waves-light">
      
      <i class="fas fa-archive" style="zoom: 0.6;"></i>
      
      <span>Archives</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/blog/about" class="waves-effect waves-light">
      
      <i class="fas fa-user-circle" style="zoom: 0.6;"></i>
      
      <span>About</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/blog/contact" class="waves-effect waves-light">
      
      <i class="fas fa-comments" style="zoom: 0.6;"></i>
      
      <span>Contact</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/blog/friends" class="waves-effect waves-light">
      
      <i class="fas fa-address-book" style="zoom: 0.6;"></i>
      
      <span>Friends</span>
    </a>
    
  </li>
  
  <li>
    <a href="#searchModal" class="modal-trigger waves-effect waves-light">
      <i id="searchIcon" class="fas fa-search" title="Search" style="zoom: 0.85;"></i>
    </a>
  </li>
</ul>


<div id="mobile-nav" class="side-nav sidenav">

    <div class="mobile-head bg-color">
        
        <img src="/blog/medias/logo.png" class="logo-img circle responsive-img">
        
        <div class="logo-name">Friats</div>
        <div class="logo-desc">
            
            Never really desperate, only the lost of the soul.
            
        </div>
    </div>

    

    <ul class="menu-list mobile-menu-list">
        
        <li class="m-nav-item">
	  
		<a href="/blog/" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-home"></i>
			
			Index
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/blog/tags" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-tags"></i>
			
			Tags
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/blog/categories" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-bookmark"></i>
			
			Categories
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/blog/archives" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-archive"></i>
			
			Archives
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/blog/about" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-user-circle"></i>
			
			About
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/blog/contact" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-comments"></i>
			
			Contact
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/blog/friends" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-address-book"></i>
			
			Friends
		</a>
          
        </li>
        
        
        <li><div class="divider"></div></li>
        <li>
            <a href="https://github.com/blinkfox/hexo-theme-matery" class="waves-effect waves-light" target="_blank">
                <i class="fab fa-github-square fa-fw"></i>Fork Me
            </a>
        </li>
        
    </ul>
</div>


        </div>

        
            <style>
    .nav-transparent .github-corner {
        display: none !important;
    }

    .github-corner {
        position: absolute;
        z-index: 10;
        top: 0;
        right: 0;
        border: 0;
        transform: scale(1.1);
    }

    .github-corner svg {
        color: #0f9d58;
        fill: #fff;
        height: 64px;
        width: 64px;
    }

    .github-corner:hover .octo-arm {
        animation: a 0.56s ease-in-out;
    }

    .github-corner .octo-arm {
        animation: none;
    }

    @keyframes a {
        0%,
        to {
            transform: rotate(0);
        }
        20%,
        60% {
            transform: rotate(-25deg);
        }
        40%,
        80% {
            transform: rotate(10deg);
        }
    }
</style>

<a href="https://github.com/blinkfox/hexo-theme-matery" class="github-corner tooltipped hide-on-med-and-down" target="_blank"
   data-tooltip="Fork Me" data-position="left" data-delay="50">
    <svg viewBox="0 0 250 250" aria-hidden="true">
        <path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path>
        <path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2"
              fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path>
        <path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z"
              fill="currentColor" class="octo-body"></path>
    </svg>
</a>
        
    </nav>

</header>

    



<div class="bg-cover pd-header post-cover" style="background-image: url('/blog/medias/featureimages/5.jpg')">
    <div class="container" style="right: 0px;left: 0px;">
        <div class="row">
            <div class="col s12 m12 l12">
                <div class="brand">
                    <h1 class="description center-align post-title">Opencv学习笔记</h1>
                </div>
            </div>
        </div>
    </div>
</div>




<main class="post-container content">

    
    <link rel="stylesheet" href="/blog/libs/tocbot/tocbot.css">
<style>
    #articleContent h1::before,
    #articleContent h2::before,
    #articleContent h3::before,
    #articleContent h4::before,
    #articleContent h5::before,
    #articleContent h6::before {
        display: block;
        content: " ";
        height: 100px;
        margin-top: -100px;
        visibility: hidden;
    }

    #articleContent :focus {
        outline: none;
    }

    .toc-fixed {
        position: fixed;
        top: 64px;
    }

    .toc-widget {
        width: 345px;
        padding-left: 20px;
    }

    .toc-widget .toc-title {
        margin: 35px 0 15px 0;
        padding-left: 17px;
        font-size: 1.5rem;
        font-weight: bold;
        line-height: 1.5rem;
    }

    .toc-widget ol {
        padding: 0;
        list-style: none;
    }

    #toc-content {
        height: calc(100vh - 250px);
        overflow: auto;
    }

    #toc-content ol {
        padding-left: 10px;
    }

    #toc-content ol li {
        padding-left: 10px;
    }

    #toc-content .toc-link:hover {
        color: #42b983;
        font-weight: 700;
        text-decoration: underline;
    }

    #toc-content .toc-link::before {
        background-color: transparent;
        max-height: 25px;

        position: absolute;
        right: 23.5vw;
        display: block;
    }

    #toc-content .is-active-link {
        color: #42b983;
    }

    #floating-toc-btn {
        position: fixed;
        right: 15px;
        bottom: 76px;
        padding-top: 15px;
        margin-bottom: 0;
        z-index: 998;
    }

    #floating-toc-btn .btn-floating {
        width: 48px;
        height: 48px;
    }

    #floating-toc-btn .btn-floating i {
        line-height: 48px;
        font-size: 1.4rem;
    }
</style>
<div class="row">
    <div id="main-content" class="col s12 m12 l9">
        <!-- 文章内容详情 -->
<div id="artDetail">
    <div class="card">
        <div class="card-content article-info">
            <div class="row tag-cate">
                <div class="col s7">
                    
                    <div class="article-tag">
                        
                            <a href="/blog/tags/Opencv/">
                                <span class="chip bg-color">Opencv</span>
                            </a>
                        
                    </div>
                    
                </div>
                <div class="col s5 right-align">
                    
                    <div class="post-cate">
                        <i class="fas fa-bookmark fa-fw icon-category"></i>
                        
                            <a href="/blog/categories/Opencv/" class="post-category">
                                Opencv
                            </a>
                        
                    </div>
                    
                </div>
            </div>

            <div class="post-info">
                
                <div class="post-date info-break-policy">
                    <i class="far fa-calendar-minus fa-fw"></i>Publish Date:&nbsp;&nbsp;
                    2020-04-03
                </div>
                

                
                <div class="post-date info-break-policy">
                    <i class="far fa-calendar-check fa-fw"></i>Update Date:&nbsp;&nbsp;
                    2020-09-07
                </div>
                

                
                <div class="info-break-policy">
                    <i class="far fa-file-word fa-fw"></i>Word Count:&nbsp;&nbsp;
                    4k
                </div>
                

                
                <div class="info-break-policy">
                    <i class="far fa-clock fa-fw"></i>Read Times:&nbsp;&nbsp;
                    15 Min
                </div>
                

                
                    <div id="busuanzi_container_page_pv" class="info-break-policy">
                        <i class="far fa-eye fa-fw"></i>Read Count:&nbsp;&nbsp;
                        <span id="busuanzi_value_page_pv"></span>
                    </div>
				
            </div>
        </div>
        <hr class="clearfix">
        <div class="card-content article-card-content">
            <div id="articleContent">
                <h1 id="前言"><a href="#前言" class="headerlink" title="前言"></a>前言</h1><p>计算机视觉在生活中已经成为了一个不可或缺的部分，下面就来总结一下我过去所学的那些关于Opencv的知识</p>
<h1 id="1-Opencv环境搭建"><a href="#1-Opencv环境搭建" class="headerlink" title="1.Opencv环境搭建"></a>1.Opencv环境搭建</h1><p>准备工作如下</p>
<ul>
<li><p>安装Python</p>
</li>
<li><p>安装pip插件</p>
</li>
<li><p>安装相关依赖包：numpy等</p>
</li>
<li><pre><code>pip install opencv-python
python
import cv2
cv2.__version__</code></pre>
</li>
</ul>
<h1 id="2-Opencv教程"><a href="#2-Opencv教程" class="headerlink" title="2.Opencv教程"></a>2.Opencv教程</h1><h2 id="2-1打开摄像头"><a href="#2-1打开摄像头" class="headerlink" title="2.1打开摄像头"></a>2.1打开摄像头</h2><pre class=" language-python"><code class="language-python"><span class="token keyword">import</span> cv2

capture <span class="token operator">=</span> cv2<span class="token punctuation">.</span>VideoCapture<span class="token punctuation">(</span><span class="token number">0</span><span class="token punctuation">)</span>
<span class="token comment" spellcheck="true">#调用电脑默认摄像头</span>

capture<span class="token punctuation">.</span>open<span class="token punctuation">(</span><span class="token number">0</span><span class="token punctuation">)</span>
<span class="token comment" spellcheck="true">#打开电脑默认摄像头</span>

<span class="token keyword">while</span><span class="token punctuation">(</span>capture<span class="token punctuation">.</span>isOpened<span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">:</span>

    ret<span class="token punctuation">,</span>frame <span class="token operator">=</span> capture<span class="token punctuation">.</span>read<span class="token punctuation">(</span><span class="token punctuation">)</span>
    <span class="token comment" spellcheck="true">#ret调用成功或失败，frame获取到的画面是一个numpy数组</span>

    cv2<span class="token punctuation">.</span>imshow<span class="token punctuation">(</span><span class="token string">'frame'</span><span class="token punctuation">,</span>frame<span class="token punctuation">)</span>
    <span class="token comment" spellcheck="true">#展示摄像头所捕获的画面，第一个参数是窗口名</span>

    key_<span class="token operator">=</span>cv2<span class="token punctuation">.</span>waitKey<span class="token punctuation">(</span><span class="token number">60</span><span class="token punctuation">)</span>
    <span class="token comment" spellcheck="true">#每60ms获取按键键值</span>

    <span class="token keyword">print</span><span class="token punctuation">(</span>key_<span class="token punctuation">)</span>

    <span class="token keyword">if</span> key_ <span class="token operator">==</span> <span class="token number">27</span><span class="token punctuation">:</span><span class="token comment" spellcheck="true">#这里27是Esc对应的键值</span>
        <span class="token keyword">break</span>

capture<span class="token punctuation">.</span>release<span class="token punctuation">(</span><span class="token punctuation">)</span>
<span class="token comment" spellcheck="true">#关闭摄像头</span>

cv2<span class="token punctuation">.</span>destroyAllWindows<span class="token punctuation">(</span><span class="token punctuation">)</span>
<span class="token comment" spellcheck="true">#关闭窗口</span></code></pre>
<p>上面是一个简单的调用摄像头的案例，其中键盘对应键值与ASCII有关</p>
<h2 id="2-2调用边缘检测"><a href="#2-2调用边缘检测" class="headerlink" title="2.2调用边缘检测"></a>2.2调用边缘检测</h2><pre class=" language-python"><code class="language-python"><span class="token comment" spellcheck="true">#边缘检测</span>
<span class="token keyword">import</span> cv2

<span class="token comment" spellcheck="true"># 回调函数，x表示滑块的位置，本例暂不使用</span>
<span class="token keyword">def</span> <span class="token function">nothing</span><span class="token punctuation">(</span>x<span class="token punctuation">)</span><span class="token punctuation">:</span>
    <span class="token keyword">pass</span>


capture <span class="token operator">=</span> cv2<span class="token punctuation">.</span>VideoCapture<span class="token punctuation">(</span><span class="token number">0</span><span class="token punctuation">)</span>
cv2<span class="token punctuation">.</span>namedWindow<span class="token punctuation">(</span><span class="token string">'frame'</span><span class="token punctuation">)</span>

cv2<span class="token punctuation">.</span>createTrackbar<span class="token punctuation">(</span><span class="token string">'MAX'</span><span class="token punctuation">,</span> <span class="token string">'frame'</span><span class="token punctuation">,</span> <span class="token number">0</span><span class="token punctuation">,</span> <span class="token number">255</span><span class="token punctuation">,</span> nothing<span class="token punctuation">)</span>
cv2<span class="token punctuation">.</span>createTrackbar<span class="token punctuation">(</span><span class="token string">'MIN'</span><span class="token punctuation">,</span> <span class="token string">'frame'</span><span class="token punctuation">,</span> <span class="token number">0</span><span class="token punctuation">,</span> <span class="token number">255</span><span class="token punctuation">,</span> nothing<span class="token punctuation">)</span>


<span class="token keyword">while</span><span class="token punctuation">(</span><span class="token boolean">True</span><span class="token punctuation">)</span><span class="token punctuation">:</span>

    MAX <span class="token operator">=</span> cv2<span class="token punctuation">.</span>getTrackbarPos<span class="token punctuation">(</span><span class="token string">'MAX'</span><span class="token punctuation">,</span> <span class="token string">'frame'</span><span class="token punctuation">)</span>
    MIN <span class="token operator">=</span> cv2<span class="token punctuation">.</span>getTrackbarPos<span class="token punctuation">(</span><span class="token string">'MIN'</span><span class="token punctuation">,</span> <span class="token string">'frame'</span><span class="token punctuation">)</span>

    ret<span class="token punctuation">,</span> frame <span class="token operator">=</span> capture<span class="token punctuation">.</span>read<span class="token punctuation">(</span><span class="token punctuation">)</span>
    edges <span class="token operator">=</span> cv2<span class="token punctuation">.</span>Canny<span class="token punctuation">(</span>frame<span class="token punctuation">,</span> MIN<span class="token punctuation">,</span> MAX<span class="token punctuation">)</span>  <span class="token comment" spellcheck="true"># canny边缘检测</span>
    teer <span class="token operator">=</span> np<span class="token punctuation">.</span>dstack<span class="token punctuation">(</span><span class="token punctuation">(</span>edges<span class="token punctuation">,</span>edges<span class="token punctuation">,</span>edges<span class="token punctuation">)</span><span class="token punctuation">)</span>

    cv2<span class="token punctuation">.</span>imshow<span class="token punctuation">(</span><span class="token string">'frame'</span><span class="token punctuation">,</span> edges<span class="token punctuation">)</span>  <span class="token comment" spellcheck="true"># 展示摄像头所捕获的画面</span>
    cv2<span class="token punctuation">.</span>imshow<span class="token punctuation">(</span><span class="token string">'teer'</span><span class="token punctuation">,</span> teer<span class="token punctuation">)</span>  <span class="token comment" spellcheck="true"># 展示摄像头所捕获的画面</span>

    <span class="token keyword">if</span> cv2<span class="token punctuation">.</span>waitKey<span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">)</span> <span class="token operator">==</span> <span class="token number">27</span><span class="token punctuation">:</span>
        <span class="token keyword">break</span>

capture<span class="token punctuation">.</span>release<span class="token punctuation">(</span><span class="token punctuation">)</span>
<span class="token comment" spellcheck="true">#关闭摄像头</span>

cv2<span class="token punctuation">.</span>destroyAllWindows<span class="token punctuation">(</span><span class="token punctuation">)</span>
<span class="token comment" spellcheck="true">#关闭窗口</span></code></pre>
<p>上面是一个自带滑块可调区间的边缘检测程序</p>
<h2 id="2-3笑脸检测"><a href="#2-3笑脸检测" class="headerlink" title="2.3笑脸检测"></a>2.3笑脸检测</h2><pre class=" language-python"><code class="language-python"><span class="token keyword">import</span> cv2

<span class="token comment" spellcheck="true"># 载入人脸检测器、眼睛检测器、微笑检测器三个级联检测器</span>
face_cascade <span class="token operator">=</span> cv2<span class="token punctuation">.</span>CascadeClassifier<span class="token punctuation">(</span>cv2<span class="token punctuation">.</span>data<span class="token punctuation">.</span>haarcascades<span class="token operator">+</span><span class="token string">'haarcascade_frontalface_default.xml'</span><span class="token punctuation">)</span>

eye_cascade <span class="token operator">=</span> cv2<span class="token punctuation">.</span>CascadeClassifier<span class="token punctuation">(</span>cv2<span class="token punctuation">.</span>data<span class="token punctuation">.</span>haarcascades<span class="token operator">+</span><span class="token string">'haarcascade_eye.xml'</span><span class="token punctuation">)</span>

smile_cascade <span class="token operator">=</span> cv2<span class="token punctuation">.</span>CascadeClassifier<span class="token punctuation">(</span>cv2<span class="token punctuation">.</span>data<span class="token punctuation">.</span>haarcascades<span class="token operator">+</span><span class="token string">'haarcascade_smile.xml'</span><span class="token punctuation">)</span>

<span class="token comment" spellcheck="true"># 调用摄像头</span>
cap <span class="token operator">=</span> cv2<span class="token punctuation">.</span>VideoCapture<span class="token punctuation">(</span><span class="token number">0</span><span class="token punctuation">)</span>

<span class="token keyword">while</span><span class="token punctuation">(</span><span class="token boolean">True</span><span class="token punctuation">)</span><span class="token punctuation">:</span>
    <span class="token comment" spellcheck="true"># 获取摄像头拍摄到的画面</span>
    ret<span class="token punctuation">,</span> frame <span class="token operator">=</span> cap<span class="token punctuation">.</span>read<span class="token punctuation">(</span><span class="token punctuation">)</span>
    faces <span class="token operator">=</span> face_cascade<span class="token punctuation">.</span>detectMultiScale<span class="token punctuation">(</span>frame<span class="token punctuation">,</span> <span class="token number">1.3</span><span class="token punctuation">,</span> <span class="token number">2</span><span class="token punctuation">)</span>
    img <span class="token operator">=</span> frame
    <span class="token keyword">for</span> <span class="token punctuation">(</span>x<span class="token punctuation">,</span>y<span class="token punctuation">,</span>w<span class="token punctuation">,</span>h<span class="token punctuation">)</span> <span class="token keyword">in</span> faces<span class="token punctuation">:</span>
        <span class="token comment" spellcheck="true"># 画出人脸框，蓝色，画笔宽度微</span>
        img <span class="token operator">=</span> cv2<span class="token punctuation">.</span>rectangle<span class="token punctuation">(</span>img<span class="token punctuation">,</span><span class="token punctuation">(</span>x<span class="token punctuation">,</span>y<span class="token punctuation">)</span><span class="token punctuation">,</span><span class="token punctuation">(</span>x<span class="token operator">+</span>w<span class="token punctuation">,</span>y<span class="token operator">+</span>h<span class="token punctuation">)</span><span class="token punctuation">,</span><span class="token punctuation">(</span><span class="token number">255</span><span class="token punctuation">,</span><span class="token number">0</span><span class="token punctuation">,</span><span class="token number">0</span><span class="token punctuation">)</span><span class="token punctuation">,</span><span class="token number">2</span><span class="token punctuation">)</span>
        <span class="token comment" spellcheck="true"># 框选出人脸区域，在人脸区域而不是全图中进行人眼检测，节省计算资源</span>
        face_area <span class="token operator">=</span> img<span class="token punctuation">[</span>y<span class="token punctuation">:</span>y<span class="token operator">+</span>h<span class="token punctuation">,</span> x<span class="token punctuation">:</span>x<span class="token operator">+</span>w<span class="token punctuation">]</span>

        <span class="token comment" spellcheck="true">## 人眼检测</span>
        <span class="token comment" spellcheck="true"># 用人眼级联分类器引擎在人脸区域进行人眼识别，返回的eyes为眼睛坐标列表</span>
        eyes <span class="token operator">=</span> eye_cascade<span class="token punctuation">.</span>detectMultiScale<span class="token punctuation">(</span>face_area<span class="token punctuation">,</span><span class="token number">1.3</span><span class="token punctuation">,</span><span class="token number">10</span><span class="token punctuation">)</span>
        <span class="token keyword">for</span> <span class="token punctuation">(</span>ex<span class="token punctuation">,</span>ey<span class="token punctuation">,</span>ew<span class="token punctuation">,</span>eh<span class="token punctuation">)</span> <span class="token keyword">in</span> eyes<span class="token punctuation">:</span>
            <span class="token comment" spellcheck="true">#画出人眼框，绿色，画笔宽度为1</span>
            cv2<span class="token punctuation">.</span>rectangle<span class="token punctuation">(</span>face_area<span class="token punctuation">,</span><span class="token punctuation">(</span>ex<span class="token punctuation">,</span>ey<span class="token punctuation">)</span><span class="token punctuation">,</span><span class="token punctuation">(</span>ex<span class="token operator">+</span>ew<span class="token punctuation">,</span>ey<span class="token operator">+</span>eh<span class="token punctuation">)</span><span class="token punctuation">,</span><span class="token punctuation">(</span><span class="token number">0</span><span class="token punctuation">,</span><span class="token number">255</span><span class="token punctuation">,</span><span class="token number">0</span><span class="token punctuation">)</span><span class="token punctuation">,</span><span class="token number">1</span><span class="token punctuation">)</span>

        <span class="token comment" spellcheck="true">## 微笑检测</span>
        <span class="token comment" spellcheck="true"># 用微笑级联分类器引擎在人脸区域进行人眼识别，返回的eyes为眼睛坐标列表</span>
        smiles <span class="token operator">=</span> smile_cascade<span class="token punctuation">.</span>detectMultiScale<span class="token punctuation">(</span>face_area<span class="token punctuation">,</span>scaleFactor<span class="token operator">=</span> <span class="token number">1.16</span><span class="token punctuation">,</span>minNeighbors<span class="token operator">=</span><span class="token number">65</span><span class="token punctuation">,</span>minSize<span class="token operator">=</span><span class="token punctuation">(</span><span class="token number">25</span><span class="token punctuation">,</span> <span class="token number">25</span><span class="token punctuation">)</span><span class="token punctuation">,</span>flags<span class="token operator">=</span>cv2<span class="token punctuation">.</span>CASCADE_SCALE_IMAGE<span class="token punctuation">)</span>
        <span class="token keyword">for</span> <span class="token punctuation">(</span>ex<span class="token punctuation">,</span>ey<span class="token punctuation">,</span>ew<span class="token punctuation">,</span>eh<span class="token punctuation">)</span> <span class="token keyword">in</span> smiles<span class="token punctuation">:</span>
            <span class="token comment" spellcheck="true">#画出微笑框，红色（BGR色彩体系），画笔宽度为1</span>
            cv2<span class="token punctuation">.</span>rectangle<span class="token punctuation">(</span>face_area<span class="token punctuation">,</span><span class="token punctuation">(</span>ex<span class="token punctuation">,</span>ey<span class="token punctuation">)</span><span class="token punctuation">,</span><span class="token punctuation">(</span>ex<span class="token operator">+</span>ew<span class="token punctuation">,</span>ey<span class="token operator">+</span>eh<span class="token punctuation">)</span><span class="token punctuation">,</span><span class="token punctuation">(</span><span class="token number">0</span><span class="token punctuation">,</span><span class="token number">0</span><span class="token punctuation">,</span><span class="token number">255</span><span class="token punctuation">)</span><span class="token punctuation">,</span><span class="token number">1</span><span class="token punctuation">)</span>
            cv2<span class="token punctuation">.</span>putText<span class="token punctuation">(</span>img<span class="token punctuation">,</span><span class="token string">'Smile'</span><span class="token punctuation">,</span><span class="token punctuation">(</span>x<span class="token punctuation">,</span>y<span class="token number">-7</span><span class="token punctuation">)</span><span class="token punctuation">,</span> <span class="token number">3</span><span class="token punctuation">,</span> <span class="token number">1.2</span><span class="token punctuation">,</span> <span class="token punctuation">(</span><span class="token number">0</span><span class="token punctuation">,</span> <span class="token number">0</span><span class="token punctuation">,</span> <span class="token number">255</span><span class="token punctuation">)</span><span class="token punctuation">,</span> <span class="token number">2</span><span class="token punctuation">,</span> cv2<span class="token punctuation">.</span>LINE_AA<span class="token punctuation">)</span>

    <span class="token comment" spellcheck="true"># 实时展示效果画面</span>
    cv2<span class="token punctuation">.</span>imshow<span class="token punctuation">(</span><span class="token string">'frame2'</span><span class="token punctuation">,</span>img<span class="token punctuation">)</span>
    <span class="token comment" spellcheck="true"># 每5毫秒监听一次键盘动作</span>
    <span class="token keyword">if</span> cv2<span class="token punctuation">.</span>waitKey<span class="token punctuation">(</span><span class="token number">5</span><span class="token punctuation">)</span> <span class="token operator">&amp;</span> <span class="token number">0xFF</span> <span class="token operator">==</span> ord<span class="token punctuation">(</span><span class="token string">'q'</span><span class="token punctuation">)</span><span class="token punctuation">:</span>
        <span class="token keyword">break</span>

<span class="token comment" spellcheck="true"># 最后，关闭所有窗口</span>
cap<span class="token punctuation">.</span>release<span class="token punctuation">(</span><span class="token punctuation">)</span>
cv2<span class="token punctuation">.</span>destroyAllWindows<span class="token punctuation">(</span><span class="token punctuation">)</span>
</code></pre>
<p>上面是一个微笑检测的程序，检测效果一般</p>
<h2 id="2-4图片处理"><a href="#2-4图片处理" class="headerlink" title="2.4图片处理"></a>2.4图片处理</h2><pre class=" language-python"><code class="language-python"><span class="token keyword">import</span> cv2

<span class="token comment" spellcheck="true"># 读入本地图像文件</span>
img <span class="token operator">=</span> cv2<span class="token punctuation">.</span>imread<span class="token punctuation">(</span><span class="token string">'logo.png'</span><span class="token punctuation">)</span>

<span class="token comment" spellcheck="true"># 在窗口中显示图像</span>
cv2<span class="token punctuation">.</span>imshow<span class="token punctuation">(</span><span class="token string">"Display window"</span><span class="token punctuation">,</span> img<span class="token punctuation">)</span>

<span class="token comment" spellcheck="true"># 获取键盘按键动作，如果按下s键，就将图像保存至本地</span>
k <span class="token operator">=</span> cv2<span class="token punctuation">.</span>waitKey<span class="token punctuation">(</span><span class="token number">0</span><span class="token punctuation">)</span> <span class="token comment" spellcheck="true"># 0表示永久等待键盘按键，15表示等待15毫秒</span>

<span class="token keyword">if</span> k <span class="token operator">==</span> ord<span class="token punctuation">(</span><span class="token string">"s"</span><span class="token punctuation">)</span><span class="token punctuation">:</span>
    cv2<span class="token punctuation">.</span>imwrite<span class="token punctuation">(</span><span class="token string">"saved_img.png"</span><span class="token punctuation">,</span> img<span class="token punctuation">)</span>

cv2<span class="token punctuation">.</span>destroyAllWindows<span class="token punctuation">(</span><span class="token punctuation">)</span>
</code></pre>
<p>简单的导入导出图片</p>
<h2 id="2-5捕获摄像头画面"><a href="#2-5捕获摄像头画面" class="headerlink" title="2.5捕获摄像头画面"></a>2.5捕获摄像头画面</h2><p>下面调用图像和摄像头，这是较为完整严谨的写法</p>
<pre class=" language-python"><code class="language-python"><span class="token keyword">import</span> cv2

<span class="token comment" spellcheck="true"># 读入本地图像文件</span>
img <span class="token operator">=</span> cv2<span class="token punctuation">.</span>imread<span class="token punctuation">(</span><span class="token string">'no_exist.png'</span><span class="token punctuation">)</span>

<span class="token comment" spellcheck="true"># 校验图像是否导入成功，如果导入失败，就输出提示</span>
<span class="token keyword">if</span> img <span class="token keyword">is</span> None<span class="token punctuation">:</span>
    <span class="token keyword">print</span><span class="token punctuation">(</span><span class="token string">"未能读入图像，请检查图像文件路径是否正确"</span><span class="token punctuation">)</span>

<span class="token comment" spellcheck="true"># 在窗口中显示图像</span>
cv2<span class="token punctuation">.</span>imshow<span class="token punctuation">(</span><span class="token string">"Display window"</span><span class="token punctuation">,</span> img<span class="token punctuation">)</span>

<span class="token comment" spellcheck="true"># 获取键盘按键动作，如果按下s键，就将图像保存至本地</span>
k <span class="token operator">=</span> cv2<span class="token punctuation">.</span>waitKey<span class="token punctuation">(</span><span class="token number">0</span><span class="token punctuation">)</span> <span class="token comment" spellcheck="true"># 0表示永久等待键盘按键，15表示等待15毫秒</span>

<span class="token keyword">if</span> k <span class="token operator">==</span> ord<span class="token punctuation">(</span><span class="token string">"s"</span><span class="token punctuation">)</span><span class="token punctuation">:</span>
    cv2<span class="token punctuation">.</span>imwrite<span class="token punctuation">(</span><span class="token string">"saved_img.png"</span><span class="token punctuation">,</span> img<span class="token punctuation">)</span>

cv2<span class="token punctuation">.</span>destroyAllWindows<span class="token punctuation">(</span><span class="token punctuation">)</span></code></pre>
<p>在实际场景中，如果图片路径没有写对，那么会报出错误，所以我们要对其进行一个人性化的处理</p>
<pre class=" language-python"><code class="language-python"><span class="token keyword">import</span> cv2

<span class="token comment" spellcheck="true"># 捕获摄像头，传入摄像头索引号，默认摄像头索引为0</span>
cap <span class="token operator">=</span> cv2<span class="token punctuation">.</span>VideoCapture<span class="token punctuation">(</span><span class="token number">0</span><span class="token punctuation">)</span>

<span class="token comment" spellcheck="true"># 校验摄像头是否捕获成功，如果未成功则输出提示</span>
<span class="token keyword">if</span> <span class="token operator">not</span> cap<span class="token punctuation">.</span>isOpened<span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">:</span>
    <span class="token keyword">print</span><span class="token punctuation">(</span><span class="token string">"无法打开摄像头"</span><span class="token punctuation">)</span>
    exit<span class="token punctuation">(</span><span class="token punctuation">)</span>

<span class="token comment" spellcheck="true"># 无限循环，直到触发break跳出</span>
<span class="token keyword">while</span> <span class="token boolean">True</span><span class="token punctuation">:</span>
    <span class="token comment" spellcheck="true"># 获取摄像头捕获的画面帧，返回ret和frame</span>
    <span class="token comment" spellcheck="true"># ret的True/False反映是否捕获成功，frame是画面</span>
    ret<span class="token punctuation">,</span> frame <span class="token operator">=</span> cap<span class="token punctuation">.</span>read<span class="token punctuation">(</span><span class="token punctuation">)</span>

    <span class="token comment" spellcheck="true"># 校验画面帧是否正确捕获，如果未成功则输出提示，跳出循环</span>
    <span class="token keyword">if</span> <span class="token operator">not</span> ret<span class="token punctuation">:</span>
        <span class="token keyword">print</span><span class="token punctuation">(</span><span class="token string">"无法获取画面帧"</span><span class="token punctuation">)</span>
        <span class="token keyword">break</span>

    <span class="token comment" spellcheck="true"># 对画面帧进行处理</span>
    <span class="token comment" spellcheck="true"># 这里是将画面转为灰度图</span>
    gray <span class="token operator">=</span> cv2<span class="token punctuation">.</span>cvtColor<span class="token punctuation">(</span>frame<span class="token punctuation">,</span> cv2<span class="token punctuation">.</span>COLOR_BGR2GRAY<span class="token punctuation">)</span>

    <span class="token comment" spellcheck="true"># 在窗口中显示处理之后的画面</span>
    cv2<span class="token punctuation">.</span>imshow<span class="token punctuation">(</span><span class="token string">'frame_window'</span><span class="token punctuation">,</span> gray<span class="token punctuation">)</span>

    <span class="token comment" spellcheck="true"># 获取键盘按键动作，如果按下q键，就跳出循环</span>
    <span class="token keyword">if</span> cv2<span class="token punctuation">.</span>waitKey<span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">)</span> <span class="token operator">==</span> ord<span class="token punctuation">(</span><span class="token string">'q'</span><span class="token punctuation">)</span><span class="token punctuation">:</span>
        <span class="token keyword">break</span>

<span class="token comment" spellcheck="true"># 关闭摄像头</span>
cap<span class="token punctuation">.</span>release<span class="token punctuation">(</span><span class="token punctuation">)</span>

<span class="token comment" spellcheck="true"># 关闭所有窗口</span>
cv2<span class="token punctuation">.</span>destroyAllWindows<span class="token punctuation">(</span><span class="token punctuation">)</span></code></pre>
<p>这里将视频内容进行了一个灰度化处理</p>
<h2 id="2-6打开视频"><a href="#2-6打开视频" class="headerlink" title="2.6打开视频"></a>2.6打开视频</h2><pre class=" language-python"><code class="language-python"><span class="token keyword">import</span> cv2
<span class="token comment" spellcheck="true">#打开一个视频,并且逐帧播放</span>
capture <span class="token operator">=</span> cv2<span class="token punctuation">.</span>VideoCapture<span class="token punctuation">(</span><span class="token string">'000.mp4'</span><span class="token punctuation">)</span>
<span class="token comment" spellcheck="true">#判断摄像头或视频是否读取，成功返回Ture</span>
<span class="token keyword">while</span><span class="token punctuation">(</span>capture<span class="token punctuation">.</span>isOpened<span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">:</span>
    temp <span class="token operator">=</span> capture<span class="token punctuation">.</span>get<span class="token punctuation">(</span>cv2<span class="token punctuation">.</span>CAP_PROP_FRAME_COUNT<span class="token punctuation">)</span>   <span class="token comment" spellcheck="true">#获取视频总帧数</span>
    <span class="token keyword">while</span><span class="token punctuation">(</span>temp<span class="token punctuation">)</span><span class="token punctuation">:</span>
        ret<span class="token punctuation">,</span> frame <span class="token operator">=</span> capture<span class="token punctuation">.</span>read<span class="token punctuation">(</span><span class="token punctuation">)</span>

        <span class="token keyword">if</span> <span class="token operator">not</span> ret<span class="token punctuation">:</span>
            <span class="token keyword">print</span><span class="token punctuation">(</span><span class="token string">"无法获取画面"</span><span class="token punctuation">)</span>
            <span class="token keyword">break</span>

        gray <span class="token operator">=</span> cv2<span class="token punctuation">.</span>cvtColor<span class="token punctuation">(</span>frame<span class="token punctuation">,</span> cv2<span class="token punctuation">.</span>COLOR_BGR2GRAY<span class="token punctuation">)</span><span class="token comment" spellcheck="true">#转化为灰度图的形式</span>

        cv2<span class="token punctuation">.</span>imshow<span class="token punctuation">(</span><span class="token string">'frame'</span><span class="token punctuation">,</span> gray<span class="token punctuation">)</span>
        temp <span class="token operator">=</span> temp <span class="token operator">-</span> <span class="token number">1</span> <span class="token comment" spellcheck="true">#播放一次帧数减一</span>
        <span class="token keyword">if</span> cv2<span class="token punctuation">.</span>waitKey<span class="token punctuation">(</span><span class="token number">30</span><span class="token punctuation">)</span> <span class="token operator">==</span> ord<span class="token punctuation">(</span><span class="token string">'q'</span><span class="token punctuation">)</span><span class="token punctuation">:</span><span class="token comment" spellcheck="true">#30表示暂停时间，越小越快</span>
            <span class="token keyword">break</span>
    <span class="token keyword">break</span></code></pre>
<h2 id="2-7录制视频保存"><a href="#2-7录制视频保存" class="headerlink" title="2.7录制视频保存"></a>2.7录制视频保存</h2><pre class=" language-python"><code class="language-python"><span class="token keyword">import</span> cv2

capture <span class="token operator">=</span> cv2<span class="token punctuation">.</span>VideoCapture<span class="token punctuation">(</span><span class="token number">0</span><span class="token punctuation">)</span>
outfile <span class="token operator">=</span> cv2<span class="token punctuation">.</span>VideoWriter<span class="token punctuation">(</span><span class="token string">'output.avi'</span><span class="token punctuation">,</span> cv2<span class="token punctuation">.</span>VideoWriter_fourcc<span class="token punctuation">(</span><span class="token operator">*</span><span class="token string">'MJPG'</span><span class="token punctuation">)</span><span class="token punctuation">,</span> <span class="token number">25.0</span><span class="token punctuation">,</span> <span class="token punctuation">(</span><span class="token number">640</span><span class="token punctuation">,</span> <span class="token number">480</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token comment" spellcheck="true">#第一个参数表示视屏录制之后的位置，第二个参数是指编码格式如mjpg格式   cv2.VideoWriter_fourcc(*'MJPG')   第三个是帧率，第四个帧大小，第五个是否彩色</span>
capture<span class="token punctuation">.</span>open<span class="token punctuation">(</span><span class="token number">0</span><span class="token punctuation">)</span>

<span class="token keyword">while</span><span class="token punctuation">(</span>capture<span class="token punctuation">.</span>isOpened<span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">:</span>
    ret<span class="token punctuation">,</span>frame <span class="token operator">=</span> capture<span class="token punctuation">.</span>read<span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token comment" spellcheck="true">#ret调用成功或失败，frame获取到的画面是一个numpy数组</span>
    outfile<span class="token punctuation">.</span>write<span class="token punctuation">(</span>frame<span class="token punctuation">)</span><span class="token comment" spellcheck="true">#写入文件</span>
    cv2<span class="token punctuation">.</span>imshow<span class="token punctuation">(</span><span class="token string">'frame'</span><span class="token punctuation">,</span>frame<span class="token punctuation">)</span><span class="token comment" spellcheck="true">#展示摄像头所捕获的画面，第一个参数是窗口名</span>

    key_<span class="token operator">=</span>cv2<span class="token punctuation">.</span>waitKey<span class="token punctuation">(</span><span class="token number">60</span><span class="token punctuation">)</span><span class="token comment" spellcheck="true">#每60ms获取按键键值</span>
    <span class="token keyword">print</span><span class="token punctuation">(</span>key_<span class="token punctuation">)</span>
    <span class="token keyword">if</span> key_ <span class="token operator">==</span> <span class="token number">27</span><span class="token punctuation">:</span><span class="token comment" spellcheck="true">#这里27是Esc对应的键值</span>
        <span class="token keyword">break</span>
capture<span class="token punctuation">.</span>release<span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token comment" spellcheck="true">#关闭摄像头</span>
cv2<span class="token punctuation">.</span>destroyAllWindows<span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token comment" spellcheck="true">#关闭窗口</span></code></pre>
<h1 id="3-1Yolo-v1技术概要"><a href="#3-1Yolo-v1技术概要" class="headerlink" title="3.1Yolo v1技术概要"></a>3.1Yolo v1技术概要</h1><p>目前YoLo已经更新到v5版本，而想要读懂YoLo我们需要从最基础的v1来看</p>
<p>YoLo是把目标检测作为回归问题去解决的</p>
<p>传统的模型需要先提取候选框，对每一个候选框逐一的甄别进行分类和回归</p>
<p>以RCNN为例先提取出两千个候选框在逐一的对每个候选框进行甄别，非常的耗时费力</p>
<p>而YoLo不一样，它是单阶段的，只需要看一次，直接将图片送入网络就可以得出结果</p>
<p>通过阅读YoLo的论文我们可以知道，YoLo是将一张图片分成一个s*s的网格，如论文上那个狗和自行车的例子，它分成了七乘七的网格，每一个网格又能预测出B个bounding box，如果在训练过程中一个标签落到了哪一个网格，那就由那个网格产生的bounding box去预测这个物体，而究竟是用这B个bounding box中的哪一个去预测呢？就是由这B个bounding box中IOU最大重合度最大的框去负责预测，网络就会产生这么一个结构7×7×（5×B+C），就是每个网格都会产生两个bounding box，每个bounding box都有五个参数分别是（x,y,h,w,c）框线粗细表示C的大小，每一个格子又会产生类别的概率，对得到的值进行后处理，比如非极大值抑制，就能的到我们最终的目标检测结果了，这就是YoLo的整个过程</p>
<p>论文中展示的过程是正向推断过程，而哪一个框预负责预测某个物体是训练的过程，训练过程是监督学习，有人工标注的矩形框的中点落在哪个格子里，就由哪个格子产生的bounding box去预测这个物体</p>
<p>YoLo v1的网络结构是一个全卷积网络，全部是由卷积神经网络构成的，中间交替使用了1×1和3×3卷积，总共有24层卷积提取图像特征，再由两个全连接层回归得到一个7×7×30的tensor，7×7意味图像分割成7×7的网格，30表示每一个各自产生两个bounding box，而每一个bounding box有五个元素，每一个格子预测二十个类别就是10+20=30</p>
<p>由于YoLo是关注图片的全部信息的，而Fast R-CNN只能看到RoI区分背景能力差，经过对比我们可以知道，区分背景和物体的能力强，但精确定位较差，而且YoLo的泛化性特别强，哪怕是在自然界中训练好的模型也能用于艺术品</p>
<h1 id="3-2YoLo-v5示例"><a href="#3-2YoLo-v5示例" class="headerlink" title="3.2YoLo v5示例"></a>3.2YoLo v5示例</h1><p>进入<a href="github.com/ultralytics/yolov5">YoLo v5</a>的github页面</p>
<p>将目标下载</p>
<p>找到下载目录并进入</p>
<p>使用Win+R打开命令行，cd到对应目录</p>
<p>运行如下命令</p>
<pre><code>python detect.py --source 0 --weights weights/yolov5s.pt</code></pre>
<p>如若报错，根据内容安装对应支持包即可</p>
<p>如：</p>
<pre><code>pip install tqdm</code></pre>
<p>torch包下载不下来可以访问<a target="_blank" rel="noopener" href="https://pytorch.org/get-started/locally/#start-locally">官网</a>选择对应的版本系统下载即可</p>
<p><img src="0.png"></p>
<p>想要关闭可以按q键退出，注意要将输入法调成英文，检测速度速度由个人电脑配置决定</p>
<p>这里我们来看一下它的源码的这个地方：</p>
<p><img src="1.png"></p>
<p>介绍一下部分参数的作用：</p>
<p>–weights    权重，可以使用默认权重文件和自己训练好的权重文件</p>
<p>–source    视频来源</p>
<p>–output    预测结果存放地址</p>
<p>–img-size    图片大小</p>
<p>–conf-thres    目标执行度阈值</p>
<p>–iou-thres    区域交并比：重叠区域和并集区域的比值</p>
<p>–device    使用CPU or GPU</p>
<p>–classes    类别</p>
<p>下面我们来尝试使用一个视频来做一个演示</p>
<p>命令如下：</p>
<pre><code>python detect.py --source 相对路径/文件名.mp4 --weights weights/yolov5s.pt --output 相对路径/文件名.mp4</code></pre>
<p>这里我们可以看到我们视频已处理帧数和总帧数，并且还有处理每一帧所耗费的时间</p>
<p><img src="2.png"></p>
<p>这里我是用CPU去跑的，所以速度很慢，如果想中途中断可以使用Ctrl+C中断，中断之后已处理的图像也会被保存下来，不过会有一些问题</p>
<h1 id="3-3使用YoLo-v5训练自己的训练集"><a href="#3-3使用YoLo-v5训练自己的训练集" class="headerlink" title="3.3使用YoLo v5训练自己的训练集"></a>3.3使用YoLo v5训练自己的训练集</h1><p>建立自己的数据集，这里举一个简单的栗子</p>
<p>标注软件建议使用Labelimg</p>
<p>操作说明，a上一张图，d下一张图，w化框格，可以用鼠标来调整，选择Yolo格式输出</p>
<p>标签文件：</p>
<p>第一列类别</p>
<p>第二列左上角坐标</p>
<p>第三列框住部分占总图片的比例</p>
<p>第四列宽度</p>
<p>第五列高度</p>
<p>以上都是归一化的值</p>
<p>每一个TXT都是一个图片上所有框的信息</p>
<hr>
<p>图片分为三个文件夹</p>
<p>训练集：用于模型拟合的数据样本</p>
<p>验证集：是模型训练过程中单独留出的样本集，它可以用于调整模型的超参数和用于对模型的能力进行初步评估</p>
<p>测试集：用来评估模最终模型的泛化能力。但不能作为调参、选择特征等算法相关的选择的依据</p>
<p>比喻一下就是</p>
<p><strong>训练集</strong>————学生的课本，学生 根据课本里的内容来掌握知识。</p>
<p><strong>验证集</strong>————作业，通过作业可以知道 不同学生学习情况、进步的速度快慢。</p>
<p><strong>测试集</strong>———–考试，考的题是平常都没有见过，考察学生举一反三的能力。</p>
<p>训练使用train.py，同时指定部分参数，data.yaml文件：里面有训练集和验证集图像的位置，类别数量和类别名；模型.yaml文件：需要根据不同训练x、s、m、l文件分别做修改，修改nc类别数，anchors可以使用聚类的方法去修改，当然这里并不建议自己修改</p>
<p>yaml文件可以使用Notepad++就可以打开和修改，当然也可以使用自带文本编辑器，不过这里不建议使用自带文本编辑器</p>
<p>总之，嫌麻烦的可以使用别人的训练集</p>
<p>官网上有相关教程，这里就不做更多介绍了</p>
<h1 id="4-1关键点检测"><a href="#4-1关键点检测" class="headerlink" title="4.1关键点检测"></a>4.1关键点检测</h1><p>关键点检测多用于检测摔倒、体育动作指导、肢体语言理解、步态身份识别、动作捕捉、动作控制、3D试衣等等场景</p>
<p>下面只聊一聊简单的关键点检测算法</p>
<p>人体关键点检测是个回归问题，这个和之前的YoLo有些相似，不过我们人体关键点检测有些限制，比如说一般人是不可能出现两个头啊六条腿之类的</p>
<p>关键点检测其实和目标追踪有些想像</p>
<p>这里顺便介绍一下计算机视觉的部分知识</p>
<p>卷积操作就是将卷积核在元组上滑动并且分别点乘，就会得到卷积后的元组</p>
<p>多通道的卷积操作就是用多通道的卷积核进行操作</p>
<p>池化是把大的元组变成小的元组，可以取最大值和平均值分为最大池化和平均池化，池化可以融合汇总特征，防止过拟合，引入平移不变性起到模糊的效果，卷积神经网络就是将卷积层与池化层交替进行最后加上全连接层和输出层构件的既可以二分类也可以多分类</p>
<p>目标检测方法包括两种</p>
<p>单阶段方法，速度快准确率低，代表：YoLo、SSD及其变种</p>
<p>两阶段方法，速度慢需要找出候选框，再在候选框上进行目标检测回归，准确率高，代表：SPP-Net、R-CNN、Fast-R-CNN、Faster-R-CNN及其变种</p>
<p>单阶段已经介绍过了，两阶段以R-CNN为例，现在目标图片上选出两千个左右的候选框，这两千多个候选框用的是选择性搜索方法，缩放成同样的大小，在分别送入神经网络中进行分类和回归，分类SVMs，回归Bbox reg；这样的速度很慢</p>
<p><img src="4.png"></p>
<p>演变过程：</p>
<p><img src="3.png"></p>
<p>说回正题</p>
<p>人体姿态估计技术：提取图像中人体的关节关键点、脸部关键点、手势关键点，构建骨架，识别姿态</p>
<p>难点：多人、姿态复杂、视频分析、三维重构</p>
<p>传统的人体姿态估计需要人工构造特征，采用”基于模型“的方法</p>
<p>深度学习大规模应用后，采用端到端的表示学习，通过数据驱动的方法自动化构建特征</p>
<p>分为从上倒下：先挑出人，再检测</p>
<p>从低而上：先把所有关节找出来，在通过一定的准则来区分不同的人</p>
<p>人体姿态估计的经典解决方案</p>
<p>卡耐基梅隆大学的<a target="_blank" rel="noopener" href="https://arxiv.org/pdf/1812.08008.pdf">OpenPose</a></p>
<p><a target="_blank" rel="noopener" href="https://github.com/CMU-Perceptual-Computing-Lab/openpose">Github源码</a></p>
<p><a target="_blank" rel="noopener" href="https://www.jianshu.com/p/3aa810b35a5d">中文翻译</a></p>
<hr>
<p><a target="_blank" rel="noopener" href="https://arxiv.org/abs/1511.06645">DeepCut</a></p>
<p><a target="_blank" rel="noopener" href="https://arxiv.org/abs/1612.00137">RMPE</a></p>
<p><a target="_blank" rel="noopener" href="https://arxiv.org/abs/1703.06870">Mask RCNN</a></p>
<p>暂时先更新到这里，后续再继续补充<del>（由于电脑配置较低实在是有些捉襟见肘）</del></p>
<script>
        document.querySelectorAll('.github-emoji')
          .forEach(el => {
            if (!el.dataset.src) { return; }
            const img = document.createElement('img');
            img.style = 'display:none !important;';
            img.src = el.dataset.src;
            img.addEventListener('error', () => {
              img.remove();
              el.style.color = 'inherit';
              el.style.backgroundImage = 'none';
              el.style.background = 'none';
            });
            img.addEventListener('load', () => {
              img.remove();
            });
            document.body.appendChild(img);
          });
      </script>
            </div>
            <hr/>

            

    <div class="reprint" id="reprint-statement">
        
            <div class="reprint__author">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-user">
                        Author:
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="/blog/about" rel="external nofollow noreferrer">Friats</a>
                </span>
            </div>
            <div class="reprint__type">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-link">
                        Link:
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="https://friats.gitee.io/blog/2020/04/03/cv-0/">https://friats.gitee.io/blog/2020/04/03/cv-0/</a>
                </span>
            </div>
            <div class="reprint__notice">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-copyright">
                        Reprint policy:
                    </i>
                </span>
                <span class="reprint-info">
                    All articles in this blog are used except for special statements
                    <a href="https://creativecommons.org/licenses/by/4.0/deed.zh" rel="external nofollow noreferrer" target="_blank">CC BY 4.0</a>
                    reprint polocy. If reproduced, please indicate source
                    <a href="/blog/about" target="_blank">Friats</a>
                    !
                </span>
            </div>
        
    </div>

    <script async defer>
      document.addEventListener("copy", function (e) {
        let toastHTML = '<span>Copied successfully, please follow the reprint policy of this article</span><button class="btn-flat toast-action" onclick="navToReprintStatement()" style="font-size: smaller">more</a>';
        M.toast({html: toastHTML})
      });

      function navToReprintStatement() {
        $("html, body").animate({scrollTop: $("#reprint-statement").offset().top - 80}, 800);
      }
    </script>



            <div class="tag_share" style="display: block;">
                <div class="post-meta__tag-list" style="display: inline-block;">
                    
                        <div class="article-tag">
                            
                                <a href="/blog/tags/Opencv/">
                                    <span class="chip bg-color">Opencv</span>
                                </a>
                            
                        </div>
                    
                </div>
                <div class="post_share" style="zoom: 80%; width: fit-content; display: inline-block; float: right; margin: -0.15rem 0;">
                    <link rel="stylesheet" type="text/css" href="/blog/libs/share/css/share.min.css">
<div id="article-share">

    
    <div class="social-share" data-sites="twitter,facebook,google,qq,qzone,wechat,weibo,douban,linkedin" data-wechat-qrcode-helper="<p>微信扫一扫即可分享！</p>"></div>
    <script src="/blog/libs/share/js/social-share.min.js"></script>
    

    

</div>

                </div>
            </div>
            
                <style>
    #reward {
        margin: 40px 0;
        text-align: center;
    }

    #reward .reward-link {
        font-size: 1.4rem;
        line-height: 38px;
    }

    #reward .btn-floating:hover {
        box-shadow: 0 6px 12px rgba(0, 0, 0, 0.2), 0 5px 15px rgba(0, 0, 0, 0.2);
    }

    #rewardModal {
        width: 320px;
        height: 350px;
    }

    #rewardModal .reward-title {
        margin: 15px auto;
        padding-bottom: 5px;
    }

    #rewardModal .modal-content {
        padding: 10px;
    }

    #rewardModal .close {
        position: absolute;
        right: 15px;
        top: 15px;
        color: rgba(0, 0, 0, 0.5);
        font-size: 1.3rem;
        line-height: 20px;
        cursor: pointer;
    }

    #rewardModal .close:hover {
        color: #ef5350;
        transform: scale(1.3);
        -moz-transform:scale(1.3);
        -webkit-transform:scale(1.3);
        -o-transform:scale(1.3);
    }

    #rewardModal .reward-tabs {
        margin: 0 auto;
        width: 210px;
    }

    .reward-tabs .tabs {
        height: 38px;
        margin: 10px auto;
        padding-left: 0;
    }

    .reward-content ul {
        padding-left: 0 !important;
    }

    .reward-tabs .tabs .tab {
        height: 38px;
        line-height: 38px;
    }

    .reward-tabs .tab a {
        color: #fff;
        background-color: #ccc;
    }

    .reward-tabs .tab a:hover {
        background-color: #ccc;
        color: #fff;
    }

    .reward-tabs .wechat-tab .active {
        color: #fff !important;
        background-color: #22AB38 !important;
    }

    .reward-tabs .alipay-tab .active {
        color: #fff !important;
        background-color: #019FE8 !important;
    }

    .reward-tabs .reward-img {
        width: 210px;
        height: 210px;
    }
</style>

<div id="reward">
    <a href="#rewardModal" class="reward-link modal-trigger btn-floating btn-medium waves-effect waves-light red">赏</a>

    <!-- Modal Structure -->
    <div id="rewardModal" class="modal">
        <div class="modal-content">
            <a class="close modal-close"><i class="fas fa-times"></i></a>
            <h4 class="reward-title">你的赏识是我前进的动力</h4>
            <div class="reward-content">
                <div class="reward-tabs">
                    <ul class="tabs row">
                        <li class="tab col s6 alipay-tab waves-effect waves-light"><a href="#alipay">支付宝</a></li>
                        <li class="tab col s6 wechat-tab waves-effect waves-light"><a href="#wechat">微 信</a></li>
                    </ul>
                    <div id="alipay">
                        <img src="/blog/medias/reward/alipay.jpg" class="reward-img" alt="支付宝打赏二维码">
                    </div>
                    <div id="wechat">
                        <img src="/blog/medias/reward/wechat.png" class="reward-img" alt="微信打赏二维码">
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    $(function () {
        $('.tabs').tabs();
    });
</script>

            
        </div>
    </div>

    

    

    

    

    

    

    

<article id="prenext-posts" class="prev-next articles">
    <div class="row article-row">
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge left-badge text-color">
                <i class="fas fa-chevron-left"></i>&nbsp;Previous</div>
            <div class="card">
                <a href="/blog/2020/04/08/moter/">
                    <div class="card-image">
                        
                        
                        <img src="/blog/medias/featureimages/5.jpg" class="responsive-img" alt="关于FOC的学习笔记">
                        
                        <span class="card-title">关于FOC的学习笔记</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            永磁同步电机控制的学习笔记！
                        
                    </div>
                    <div class="publish-info">
                        <span class="publish-date">
                            <i class="far fa-clock fa-fw icon-date"></i>2020-04-08
                        </span>
                        <span class="publish-author">
                            
                            <i class="fas fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/blog/categories/%E7%94%B5%E6%9C%BA%E6%8E%A7%E5%88%B6/" class="post-category">
                                    电机控制
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/blog/tags/%E7%94%B5%E6%9C%BA%E6%8E%A7%E5%88%B6/">
                        <span class="chip bg-color">电机控制</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge right-badge text-color">
                Next&nbsp;<i class="fas fa-chevron-right"></i>
            </div>
            <div class="card">
                <a href="/blog/2020/03/29/pid-1/">
                    <div class="card-image">
                        
                        
                        <img src="/blog/medias/featureimages/22.jpg" class="responsive-img" alt="模糊PID二">
                        
                        <span class="card-title">模糊PID二</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            关于模糊PID的一些学习以及笔记！
                        
                    </div>
                    <div class="publish-info">
                            <span class="publish-date">
                                <i class="far fa-clock fa-fw icon-date"></i>2020-03-29
                            </span>
                        <span class="publish-author">
                            
                            <i class="fas fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/blog/categories/PID/" class="post-category">
                                    PID
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/blog/tags/%E6%A8%A1%E7%B3%8APID/">
                        <span class="chip bg-color">模糊PID</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
    </div>
</article>

</div>



<!-- 代码块功能依赖 -->
<script type="text/javascript" src="/blog/libs/codeBlock/codeBlockFuction.js"></script>

<!-- 代码语言 -->

<script type="text/javascript" src="/blog/libs/codeBlock/codeLang.js"></script>


<!-- 代码块复制 -->

<script type="text/javascript" src="/blog/libs/codeBlock/codeCopy.js"></script>


<!-- 代码块收缩 -->

<script type="text/javascript" src="/blog/libs/codeBlock/codeShrink.js"></script>


<!-- 代码块折行 -->

<style type="text/css">
code[class*="language-"], pre[class*="language-"] { white-space: pre !important; }
</style>


    </div>
    <div id="toc-aside" class="expanded col l3 hide-on-med-and-down">
        <div class="toc-widget">
            <div class="toc-title"><i class="far fa-list-alt"></i>&nbsp;&nbsp;TOC</div>
            <div id="toc-content"></div>
        </div>
    </div>
</div>

<!-- TOC 悬浮按钮. -->

<div id="floating-toc-btn" class="hide-on-med-and-down">
    <a class="btn-floating btn-large bg-color">
        <i class="fas fa-list-ul"></i>
    </a>
</div>


<script src="/blog/libs/tocbot/tocbot.min.js"></script>
<script>
    $(function () {
        tocbot.init({
            tocSelector: '#toc-content',
            contentSelector: '#articleContent',
            headingsOffset: -($(window).height() * 0.4 - 45),
            collapseDepth: Number('0'),
            headingSelector: 'h2, h3, h4'
        });

        // modify the toc link href to support Chinese.
        let i = 0;
        let tocHeading = 'toc-heading-';
        $('#toc-content a').each(function () {
            $(this).attr('href', '#' + tocHeading + (++i));
        });

        // modify the heading title id to support Chinese.
        i = 0;
        $('#articleContent').children('h2, h3, h4').each(function () {
            $(this).attr('id', tocHeading + (++i));
        });

        // Set scroll toc fixed.
        let tocHeight = parseInt($(window).height() * 0.4 - 64);
        let $tocWidget = $('.toc-widget');
        $(window).scroll(function () {
            let scroll = $(window).scrollTop();
            /* add post toc fixed. */
            if (scroll > tocHeight) {
                $tocWidget.addClass('toc-fixed');
            } else {
                $tocWidget.removeClass('toc-fixed');
            }
        });

        
        /* 修复文章卡片 div 的宽度. */
        let fixPostCardWidth = function (srcId, targetId) {
            let srcDiv = $('#' + srcId);
            if (srcDiv.length === 0) {
                return;
            }

            let w = srcDiv.width();
            if (w >= 450) {
                w = w + 21;
            } else if (w >= 350 && w < 450) {
                w = w + 18;
            } else if (w >= 300 && w < 350) {
                w = w + 16;
            } else {
                w = w + 14;
            }
            $('#' + targetId).width(w);
        };

        // 切换TOC目录展开收缩的相关操作.
        const expandedClass = 'expanded';
        let $tocAside = $('#toc-aside');
        let $mainContent = $('#main-content');
        $('#floating-toc-btn .btn-floating').click(function () {
            if ($tocAside.hasClass(expandedClass)) {
                $tocAside.removeClass(expandedClass).hide();
                $mainContent.removeClass('l9');
            } else {
                $tocAside.addClass(expandedClass).show();
                $mainContent.addClass('l9');
            }
            fixPostCardWidth('artDetail', 'prenext-posts');
        });
        
    });
</script>

    

</main>




    <footer class="page-footer bg-color">
    
        <link rel="stylesheet" href="/blog/libs/aplayer/APlayer.min.css">
<style>
    .aplayer .aplayer-lrc p {
        
        display: none;
        
        font-size: 12px;
        font-weight: 700;
        line-height: 16px !important;
    }

    .aplayer .aplayer-lrc p.aplayer-lrc-current {
        
        display: none;
        
        font-size: 15px;
        color: #0F2540;
    }

    
    .aplayer.aplayer-fixed.aplayer-narrow .aplayer-body {
        left: -66px !important;
    }

    .aplayer.aplayer-fixed.aplayer-narrow .aplayer-body:hover {
        left: 0px !important;
    }

    
</style>
<div class="">
    
    <div class="row">
        <meting-js class="col l8 offset-l2 m10 offset-m1 s12"
                   server="tencent"
                   type="playlist"
                   id="7567797652#503838841"
                   fixed='true'
                   autoplay='false'
                   theme='#0F2540'
                   loop='all'
                   order='random'
                   preload='auto'
                   volume='0.7'
                   list-folded='true'
        >
        </meting-js>
    </div>
</div>

<script src="/blog/libs/aplayer/APlayer.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/meting@2/dist/Meting.min.js"></script>

    
    <div class="container row center-align" style="margin-bottom: 0px !important;">
        <div class="col s12 m8 l8 copy-right">
            Copyright&nbsp;&copy;
            <span id="year">2019</span>
            <a href="/blog/about" target="_blank">friats</a>
            |&nbsp;Powered by&nbsp;<a href="https://hexo.io/" target="_blank">Hexo</a>
            |&nbsp;Theme&nbsp;<a href="https://github.com/blinkfox/hexo-theme-matery" target="_blank">Matery</a>
            <br>
            
            &nbsp;<i class="fas fa-chart-area"></i>&nbsp;站点总字数:&nbsp;<span
                class="white-color">22.4k</span>&nbsp;字
            
            
            
            
            
            
            <span id="busuanzi_container_site_pv">
                |&nbsp;<i class="far fa-eye"></i>&nbsp;总访问量:&nbsp;<span id="busuanzi_value_site_pv"
                    class="white-color"></span>&nbsp;次
            </span>
            
            
            <span id="busuanzi_container_site_uv">
                |&nbsp;<i class="fas fa-users"></i>&nbsp;总访问人数:&nbsp;<span id="busuanzi_value_site_uv"
                    class="white-color"></span>&nbsp;人
            </span>
            
            <br>
            
            <br>
            
        </div>
        <div class="col s12 m4 l4 social-link">
    <a href="https://github.com/Friats" class="tooltipped" target="_blank" data-tooltip="访问我的GitHub" data-position="top" data-delay="50">
        <i class="fab fa-github"></i>
    </a>



    <a href="mailto:2393250872@qq.com" class="tooltipped" target="_blank" data-tooltip="邮件联系我" data-position="top" data-delay="50">
        <i class="fas fa-envelope-open"></i>
    </a>







    <a href="tencent://AddContact/?fromId=50&fromSubId=1&subcmd=all&uin=2393250872" class="tooltipped" target="_blank" data-tooltip="QQ联系我: 2393250872" data-position="top" data-delay="50">
        <i class="fab fa-qq"></i>
    </a>







    <a href="/blog/atom.xml" class="tooltipped" target="_blank" data-tooltip="RSS 订阅" data-position="top" data-delay="50">
        <i class="fas fa-rss"></i>
    </a>

</div>
    </div>
</footer>

<div class="progress-bar"></div>


    <!-- 搜索遮罩框 -->
<div id="searchModal" class="modal">
    <div class="modal-content">
        <div class="search-header">
            <span class="title"><i class="fas fa-search"></i>&nbsp;&nbsp;Search</span>
            <input type="search" id="searchInput" name="s" placeholder="Please enter a search keyword"
                   class="search-input">
        </div>
        <div id="searchResult"></div>
    </div>
</div>

<script src="/blog/js/search.js"></script>
<script type="text/javascript">
$(function () {
    searchFunc("/blog/search.xml", 'searchInput', 'searchResult');
});
</script>

    <!-- 回到顶部按钮 -->
<div id="backTop" class="top-scroll">
    <a class="btn-floating btn-large waves-effect waves-light" href="#!">
        <i class="fas fa-arrow-up"></i>
    </a>
</div>



<script src="https://cdn.jsdelivr.net/gh/wallleap/cdn/js/noSomeKey.js"></script>

<script src="https://cdn.jsdelivr.net/gh/wallleap/cdn/js/sakura.js"></script>

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/font-awesome/css/font-awesome.min.css">
<script src="https://cdn.jsdelivr.net/gh/stevenjoezhang/live2d-widget@latest/autoload.js"></script>

<script src="//instant.page/3.0.0" type="module" defer integrity="sha384-OeDn4XE77tdHo8pGtE1apMPmAipjoxUQ++eeJa6EtJCfHlvijigWiJpD7VDPWXV1"></script>



    <script src="/blog/libs/materialize/materialize.min.js"></script>
    <script src="/blog/libs/masonry/masonry.pkgd.min.js"></script>
    <script src="/blog/libs/aos/aos.js"></script>
    <script src="/blog/libs/scrollprogress/scrollProgress.min.js"></script>
    <script src="/blog/libs/lightGallery/js/lightgallery-all.min.js"></script>
    <script src="/blog/js/matery.js"></script>

    <!-- Baidu Analytics -->

    <!-- Baidu Push -->

<script>
    (function () {
        var bp = document.createElement('script');
        var curProtocol = window.location.protocol.split(':')[0];
        if (curProtocol === 'https') {
            bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';
        } else {
            bp.src = 'http://push.zhanzhang.baidu.com/push.js';
        }
        var s = document.getElementsByTagName("script")[0];
        s.parentNode.insertBefore(bp, s);
    })();
</script>

    
    <script src="/blog/libs/others/clicklove.js" async="async"></script>
    
    
    <script async src="/blog/libs/others/busuanzi.pure.mini.js"></script>
    

    

    

    

    
    
    <script type="text/javascript" size="150" alpha='0.6'
        zIndex="-1" src="/blog/libs/background/ribbon-refresh.min.js" async="async"></script>
    

    

    
    <script src="/blog/libs/instantpage/instantpage.js" type="module"></script>
    

</body>

</html>
